﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 产品表服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class productsService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Products> _productsRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public productsService(SqlSugarRepository<Products> productsRep, ISqlSugarClient sqlSugarClient)
    {
        _productsRep = productsRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询产品表 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询产品表")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<productsOutput>> Page(PageproductsInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _productsRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.ProductsEncode.Contains(input.Keyword) || u.ProductsName.Contains(input.Keyword) || u.ExpirationDate.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductsEncode), u => u.ProductsEncode.Contains(input.ProductsEncode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProductsName), u => u.ProductsName.Contains(input.ProductsName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ExpirationDate), u => u.ExpirationDate.Contains(input.ExpirationDate.Trim()))
            .WhereIF(input.SpecificationsId != null, u => u.SpecificationsId == input.SpecificationsId)
            .WhereIF(input.ModelId != null, u => u.ModelId == input.ModelId)
            .WhereIF(input.VendorId != null, u => u.VendorId == input.VendorId)
            .WhereIF(input.MeteringUnitId != null, u => u.MeteringUnitId == input.MeteringUnitId)
            .WhereIF(input.ClassifyId != null, u => u.ClassifyId == input.ClassifyId)
            .LeftJoin<Specifications>((u, specifications) => u.SpecificationsId == specifications.Id)
            .LeftJoin<Model>((u, specifications, model) => u.ModelId == model.Id)
            .LeftJoin<Vendor>((u, specifications, model, vendor) => u.VendorId == vendor.Id)
            .LeftJoin<Meteringunit>((u, specifications, model, vendor, meteringUnit) => u.MeteringUnitId == meteringUnit.Id)
            .LeftJoin<Classify>((u, specifications, model, vendor, meteringUnit, classify) => u.ClassifyId == classify.Id)
            .Select((u, specifications, model, vendor, meteringUnit, classify) => new productsOutput
            {
                Id = u.Id,
                ProductsEncode = u.ProductsEncode,
                ProductsName = u.ProductsName,
                SpecificationsId = u.SpecificationsId,
                SpecificationsFkDisplayName = $"{specifications.SpecificationsName}",
                ModelId = u.ModelId,
                ModelFkDisplayName = $"{model.ModelName}",
                VendorId = u.VendorId,
                VendorFkDisplayName = $"{vendor.VendorName}",
                ExpirationDate = u.ExpirationDate,
                MeteringUnitId = u.MeteringUnitId,
                MeteringUnitFkDisplayName = $"{meteringUnit.UnitName}",
                ClassifyId = u.ClassifyId,
                ClassifyFkDisplayName = $"{classify.ClassifyName}",
                IsEnable = u.IsEnable,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取产品表详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取产品表详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Products> Detail([FromQuery] QueryByIdproductsInput input)
    {
        return await _productsRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加产品表 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加产品表")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddproductsInput input)
    {
        var entity = input.Adapt<Products>();
        return await _productsRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新产品表 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新产品表")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateproductsInput input)
    {
        var entity = input.Adapt<Products>();
        await _productsRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除产品表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除产品表")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteproductsInput input)
    {
        var entity = await _productsRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _productsRep.FakeDeleteAsync(entity);   //假删除
        //await _productsRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除产品表 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除产品表")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteproductsInput> input)
    {
        var exp = Expressionable.Create<Products>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _productsRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _productsRep.FakeDeleteAsync(list);   //假删除
        //return await _productsRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataproductsInput input)
    {
        var specificationsIdData = await _productsRep.Context.Queryable<Specifications>()
            .InnerJoinIF<Products>(input.FromPage, (u, r) => u.Id == r.SpecificationsId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.SpecificationsName}"
            }).ToListAsync();
        var modelIdData = await _productsRep.Context.Queryable<Model>()
            .InnerJoinIF<Products>(input.FromPage, (u, r) => u.Id == r.ModelId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ModelName}"
            }).ToListAsync();
        var vendorIdData = await _productsRep.Context.Queryable<Vendor>()
            .InnerJoinIF<Products>(input.FromPage, (u, r) => u.Id == r.VendorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var meteringUnitIdData = await _productsRep.Context.Queryable<Meteringunit>()
            .InnerJoinIF<Products>(input.FromPage, (u, r) => u.Id == r.MeteringUnitId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UnitName}"
            }).ToListAsync();
        var classifyIdData = await _productsRep.Context.Queryable<Classify>()
            .InnerJoinIF<Products>(input.FromPage, (u, r) => u.Id == r.ClassifyId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.ClassifyName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "specificationsId", specificationsIdData },
            { "modelId", modelIdData },
            { "vendorId", vendorIdData },
            { "meteringUnitId", meteringUnitIdData },
            { "classifyId", classifyIdData },
        };
    }
    
    /// <summary>
    /// 导出产品表记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出产品表记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageproductsInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportproductsOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "产品表导出记录");
    }
    
    /// <summary>
    /// 下载产品表数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载产品表数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportproductsOutput>(), "产品表导入模板", (_, info) =>
        {
            if (nameof(ExportproductsOutput.SpecificationsFkDisplayName) == info.Name) return _productsRep.Context.Queryable<Specifications>().Select(u => $"{u.SpecificationsName}").Distinct().ToList();
            if (nameof(ExportproductsOutput.ModelFkDisplayName) == info.Name) return _productsRep.Context.Queryable<Model>().Select(u => $"{u.ModelName}").Distinct().ToList();
            if (nameof(ExportproductsOutput.VendorFkDisplayName) == info.Name) return _productsRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportproductsOutput.MeteringUnitFkDisplayName) == info.Name) return _productsRep.Context.Queryable<Meteringunit>().Select(u => $"{u.UnitName}").Distinct().ToList();
            if (nameof(ExportproductsOutput.ClassifyFkDisplayName) == info.Name) return _productsRep.Context.Queryable<Classify>().Select(u => $"{u.ClassifyName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入产品表记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入产品表记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportproductsInput, Products>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 规格
                    var specificationsIdLabelList = pageItems.Where(x => x.SpecificationsFkDisplayName != null).Select(x => x.SpecificationsFkDisplayName).Distinct().ToList();
                    if (specificationsIdLabelList.Any()) {
                        var specificationsIdLinkMap = _productsRep.Context.Queryable<Specifications>().Where(u => specificationsIdLabelList.Contains($"{u.SpecificationsName}")).ToList().ToDictionary(u => $"{u.SpecificationsName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.SpecificationsId = specificationsIdLinkMap.GetValueOrDefault(e.SpecificationsFkDisplayName ?? "");
                            if (e.SpecificationsId == null) e.Error = "规格链接失败";
                        });
                    }
                    // 链接 型号
                    var modelIdLabelList = pageItems.Where(x => x.ModelFkDisplayName != null).Select(x => x.ModelFkDisplayName).Distinct().ToList();
                    if (modelIdLabelList.Any()) {
                        var modelIdLinkMap = _productsRep.Context.Queryable<Model>().Where(u => modelIdLabelList.Contains($"{u.ModelName}")).ToList().ToDictionary(u => $"{u.ModelName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ModelId = modelIdLinkMap.GetValueOrDefault(e.ModelFkDisplayName ?? "");
                            if (e.ModelId == null) e.Error = "型号链接失败";
                        });
                    }
                    // 链接 供应商
                    var vendorIdLabelList = pageItems.Where(x => x.VendorFkDisplayName != null).Select(x => x.VendorFkDisplayName).Distinct().ToList();
                    if (vendorIdLabelList.Any()) {
                        var vendorIdLinkMap = _productsRep.Context.Queryable<Vendor>().Where(u => vendorIdLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.VendorId = vendorIdLinkMap.GetValueOrDefault(e.VendorFkDisplayName ?? "");
                            if (e.VendorId == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 计量单位
                    var meteringUnitIdLabelList = pageItems.Where(x => x.MeteringUnitFkDisplayName != null).Select(x => x.MeteringUnitFkDisplayName).Distinct().ToList();
                    if (meteringUnitIdLabelList.Any()) {
                        var meteringUnitIdLinkMap = _productsRep.Context.Queryable<Meteringunit>().Where(u => meteringUnitIdLabelList.Contains($"{u.UnitName}")).ToList().ToDictionary(u => $"{u.UnitName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.MeteringUnitId = meteringUnitIdLinkMap.GetValueOrDefault(e.MeteringUnitFkDisplayName ?? "");
                            if (e.MeteringUnitId == null) e.Error = "计量单位链接失败";
                        });
                    }
                    // 链接 分类
                    var classifyIdLabelList = pageItems.Where(x => x.ClassifyFkDisplayName != null).Select(x => x.ClassifyFkDisplayName).Distinct().ToList();
                    if (classifyIdLabelList.Any()) {
                        var classifyIdLinkMap = _productsRep.Context.Queryable<Classify>().Where(u => classifyIdLabelList.Contains($"{u.ClassifyName}")).ToList().ToDictionary(u => $"{u.ClassifyName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.ClassifyId = classifyIdLinkMap.GetValueOrDefault(e.ClassifyFkDisplayName ?? "");
                            if (e.ClassifyId == null) e.Error = "分类链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.SpecificationsId == null){
                            x.Error = "规格不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ModelId == null){
                            x.Error = "型号不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.VendorId == null){
                            x.Error = "供应商不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.MeteringUnitId == null){
                            x.Error = "计量单位不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ClassifyId == null){
                            x.Error = "分类不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.IsEnable == null){
                            x.Error = "是否启用不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<Products>>();
                    
                    var storageable = _productsRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.ProductsEncode), "物料编码不能为空")
                        .SplitError(it => it.Item.ProductsEncode?.Length > 32, "物料编码长度不能超过32个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.ProductsName), "物料名称不能为空")
                        .SplitError(it => it.Item.ProductsName?.Length > 32, "物料名称长度不能超过32个字符")
                        .SplitError(it => it.Item.SpecificationsId == null, "规格不能为空")
                        .SplitError(it => it.Item.ModelId == null, "型号不能为空")
                        .SplitError(it => it.Item.VendorId == null, "供应商不能为空")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.ExpirationDate), "有效日期不能为空")
                        .SplitError(it => it.Item.ExpirationDate?.Length > 32, "有效日期长度不能超过32个字符")
                        .SplitError(it => it.Item.MeteringUnitId == null, "计量单位不能为空")
                        .SplitError(it => it.Item.ClassifyId == null, "分类不能为空")
                        .SplitError(it => it.Item.IsEnable == null, "是否启用不能为空")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
